#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : wupeiqi_async
@File : 11-async_contextmanager.py
@Author : Royce
@Time : 2025/7/13 11:27  
@脚本说明 : 
"""
import asyncio
import uvloop

from util.util import timer


class AsyncContextManager:
    def __init__(self, conn):
        self.conn = conn

    @timer('ms')
    async def do_something(self):
        # 异步操作数据库
        await asyncio.sleep(2)
        return 666

    async def __aenter__(self):
        # 异步链接数据库
        self.conn = await asyncio.sleep(1)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        # 异步关闭数据库链接
        await asyncio.sleep(1)


async def func():
    async with AsyncContextManager(None) as f:
        result = await f.do_something()
        print(result)


if __name__ == '__main__':
    asyncio.run(func())
